package com.cares.core.base.service;

import java.util.HashMap;
import java.util.Map;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.mapper.JsonMapper;
import org.springside.modules.utils.DateProvider;

import com.cares.core.base.mybatis.BaseMybatisDao;
import com.cares.core.mng.service.ShiroDbRealm.ShiroUser;

/**
 * 基础oracle Service抽象类 使用TourGroup数据源及回滚
 * 
 * @author xmarsx
 * @create 2013-7-24 下午7:27:33
 */

@Component
@Transactional(value = "CORE-DB", rollbackFor = Exception.class)
public class BaseService {

	protected BaseMybatisDao baseDao;

	private final JsonMapper jsonMapper = JsonMapper.nonDefaultMapper();
	
	protected DateProvider dateProvider = DateProvider.DEFAULT;

	/**
	 * 
	 * @param sequence
	 * @return
	 */
	public Long getSequence(String sequence) {
		return baseDao.getSequence(sequence);
	}
	
	public Long getTableKey(String tableName) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("tableName", tableName);
		params.put("keyValue", 0);
		baseDao.getTableKey(params);
		return (Long) params.get("keyValue");
	}

	/**
	 * 取出Shiro中的当前用户LoginName.
	 */
	public String getCurrentUserName() {
		ShiroUser user = getCurrentUser();
		if (user == null)
			return "";
		return user.getLoginName();
	}

	public String getCurrentUserOrgCode() {
		ShiroUser user = getCurrentUser();
		if (user == null)
			return null;
		return user.getOrgCode();
	}

	public Long getCurrentUserOrgId() {
		ShiroUser user = getCurrentUser();
		if (user == null)
			return null;
		return user.getOrgId();
	}
	
	public String getCurrentUserOrgPath() {
		ShiroUser user = getCurrentUser();
		if (user == null)
			return null;
		return user.getOrgPath();
	}
	
	public String getCurrentUserOrgType() {
		ShiroUser user = getCurrentUser();
		if (user == null)
			return null;
		return user.getOrgType();
	}

	/**
	 * 取出Shiro中的当前用户.
	 */
	public ShiroUser getCurrentUser() {
		if (null == SecurityUtils.getSubject())
			return null;
		ShiroUser user = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
		return user;
	}

	public Subject getSubject() {
		if (null == SecurityUtils.getSubject())
			return null;
		return SecurityUtils.getSubject();
	}

	public boolean isPermmit(String authCode) {
		if (null == SecurityUtils.getSubject())
			return false;
		return SecurityUtils.getSubject().isPermitted(authCode);
	}

	/**
	 * 根据orgPath 生成临时表数据：含当前机构的所有子机构
	 * 临时表：TE_ORGNIZATION
	 * @param orgPath
	 */
	public void updateFilterOrgnization(String orgPath) {
		baseDao.updateFilterOrgnization(orgPath);
	}

}
